package com.aoxun.android.commons.base;
/**
 * Created by Onelong on 2017/11/20.
 */

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.IdRes;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.aoxun.android.gridmanager.R;
import com.githang.statusbar.StatusBarCompat;
import com.socks.library.KLog;
import com.aoxun.android.commons.IAppDelegate;
import com.aoxun.android.commons.ICreateCallback;
import com.aoxun.android.commons.IFinishable;
import com.aoxun.android.commons.IMessageHandler;
import com.aoxun.android.commons.impl.BaseMessageHandler;
import com.aoxun.android.commons.impl.BaseUiDelegate;
import com.aoxun.android.commons.impl.FinishableStack;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;


public abstract class BaseActivity extends RxAppCompatActivity implements IFinishable,
        ICreateCallback {
    private static int sStartedActivityCount;
    //注入
    public BaseUiDelegate uiDelegate;
    //注入
    public IAppDelegate appDelegate;
    //注入，//用于组件直接通信
    private IMessageHandler messageHandler;

    private String TAG;

    private Disposable mDisposable;

    private InputMethodManager manager;

    protected Consumer<Object> loadingShowAction = new Consumer<Object>() {
        @Override
        public void accept(@NonNull Object o) throws Exception {
            KLog.d("start event------>");
            Observable.just(1)//.delay(200, TimeUnit.MILLISECONDS) //延时200毫秒
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnDispose(new Action() {
                        @Override
                        public void run() throws Exception {
                            getUiDelegate().dismissLoadingDlg();
                        }
                    })
                    .subscribe(new Observer<Integer>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable disposable) {
                            mDisposable = disposable;
                        }
                        @Override
                        public void onNext(@NonNull Integer integer) {
                            getUiDelegate().showLoadingDlg();
                        }
                        @Override
                        public void onError(@NonNull Throwable throwable) {}
                        @Override
                        public void onComplete() {}
                    });
        }
    };

    protected Action loadingHideAction = new Action() {
        @Override
        public void run() throws Exception {
            KLog.d("end event<------");
            if (!mDisposable.isDisposed()) {
                mDisposable.dispose();
            }
            getUiDelegate().dismissLoadingDlg();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        FinishableStack.putFinishList(this);
        TAG = getClass().getName();
        getUiDelegate();

        messageHandler = new BaseMessageHandler(this);

        setContentView(getLayoutId());
        initView();
        setListener();
        initData(savedInstanceState);

        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        //int color = Color.BLACK;//#3D4363

        StatusBarCompat.setStatusBarColor(this,getResources().getColor(R.color.colorPrimary));
    }


    @Override
    public void finish() {
        FinishableStack.removeFromFinishList(this);
        super.finish();
    }

    @Override
    final public void exit() {
        try {
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        sStartedActivityCount++;
        if (1 == sStartedActivityCount && appDelegate != null) {
            appDelegate.applicationDidEnterForeground();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        sStartedActivityCount--;
        if (0 == sStartedActivityCount && appDelegate != null) {
            appDelegate.applicationDidEnterBackground();
        }
    }


    @Override
    protected void onDestroy() {
        if (messageHandler != null) {
            messageHandler.destory();
        }
        messageHandler = null;
/*
        if (uiDelegate != null) {
            uiDelegate.destory();
        }
        */
        uiDelegate = null;
        super.onDestroy();
//        ImmersionBar.with(this).destroy();
    }

    public abstract void handleMessage(Message msg);

    public BaseUiDelegate getUiDelegate() {
        if (uiDelegate == null) {
            uiDelegate = BaseUiDelegate.create(this);
        }
        return uiDelegate;
    }

    public IMessageHandler getMessageHandler(){
        return messageHandler;
    }

    //-----------------------------------------------
    public <T extends View> T find(@IdRes int viewId) {
        return (T) this.findViewById(viewId);
    }

    /**
     * 获取输入框的文本
     *
     * @param e
     * @return
     */
    public String getEditTextString(EditText e) {
        String str;
        str = (e == null ? "" : e.getText().toString().trim());
        return str;
    }

    /**
     * 文本编辑器是否有输入内容
     *
     * @param et
     * @return true代表没有输入内容
     */
    public boolean checkEditContentIsNull(EditText et) {
        if (et == null) {
            return true;
        } else {
            if (!getEditTextString(et).equals("")) {
                return false;
            }
        }
        return true;
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            if(getCurrentFocus()!=null && getCurrentFocus().getWindowToken()!=null){
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }
}